export const activityTypeList = {
  '交友': '#F6A417',
  '亲子': '#1FD42E',
  '便民': '#399EFE',
  '公益': '#F0637A'
}
export const colorList = {
  0: '#F0637A', // 4 % 4 = 0
  1: '#F6A417',
  2: '#1FD42E',
  3: '#399EFE'
}
export const noticeTypeList = {
  '提示': '#F6A417',
  '活动': '#1FD42E',
  '重要公告': '#399EFE',
  '紧急公告': '#F0637A'
};

export const setIotToken = (tokenObj) => {
  if (tokenObj?.token) {
    uni.setStorageSync('iotToken', JSON.stringify(tokenObj));
  }
};

export const getIotToken = () => {
  const iotStr = uni.getStorageSync('iotToken') || '{}';
  const iotObj = JSON.parse(iotStr);

  if (!iotObj.token) {
    return '';
  }

  const { token, time } = iotObj;
  const nowTime = new Date().getTime();
  const tokenTime = new Date(time).getTime();
  if (nowTime - tokenTime > 3500 * 1000) {
    uni.removeStorageSync('iotToken');
    return '';
  }

  return token;
};
export function randomNum(m, n) {
	return Math.ceil(Math.random() * (n-m+1) + m-1)
};
export function saveAlbum(fn) {//获取权限保存相册
  uni.getSetting({//获取用户的当前设置
    success: (res) => {
      // console.log("获取权限",res);
      if (res.authSetting['scope.writePhotosAlbum']) {//验证用户是否授权可以访问相册
        this.saveImageToPhotosAlbum();
      } else {
        uni.authorize({//如果没有授权，向用户发起请求
          scope: 'scope.writePhotosAlbum',
          success: () => {
            fn()
          },
          fail: () => {
            uni.showToast({
              title: "请打开保存相册权限，再点击保存相册分享",
              icon: "none",
              duration: 3000
            });
            setTimeout(() => {
              uni.openSetting({//调起客户端小程序设置界面,让用户开启访问相册
                success: (res2) => {
                  // console.log(res2.authSetting)
                }
              });
            }, 3000);
          }
        })
      }
    }
  })
}
export function saveImageToPhotosAlbum(base64Img) {
  let base64 = base64Img.replace(/^data:image\/\w+;base64,/, "");//去掉data:image/png;base64,
  let filePath = wx.env.USER_DATA_PATH + `/${this.$u.guid(8)}.png`;
  uni.getFileSystemManager().writeFile({
    filePath: filePath,  //创建一个临时文件名
    data: base64,    //写入的文本或二进制数据
    encoding: 'base64',  //写入当前文件的字符编码
    success: res => {
      uni.saveImageToPhotosAlbum({
        filePath: filePath,
        success: function (res2) {
          uni.showToast({
            title: '保存成功，请从相册选择再分享',
            icon: "none",
            duration: 5000
          })
        },
        fail: function (err) {
          // console.log(err.errMsg);
        }
      })
    },
    fail: err => {
      //console.log(err)
    }
  })
}
// 百度坐标bd09 –> 火星坐标gcj02
export function convertLngAndLat (lng,lat) {
    var X_PI = (Math.PI * 3000.0) / 180.0
    var x = lng - 0.0065,
        y = lat - 0.006
    var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * X_PI)
    var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI)
    var bd_lng = z * Math.cos(theta)
    var bd_lat = z * Math.sin(theta)
    return {
        lng: bd_lng,
        lat: bd_lat
    }
}

export function parseUrlParams(paramString) {
	const result = {};
	  
	if (!paramString) return result;
	  
	paramString.split('&').forEach(param => {
		const [key, value] = param.split('=');
		if (key) {
			result[decodeURIComponent(key)] = decodeURIComponent(value || '');
		}
	});
	  
	return result;
}
// 跳转外部小程序
export function jumpExternalMini(h5Url, tabId) {
	const hasAppIdWords = h5Url.toLowerCase().includes('appid')
	if (!hasAppIdWords) {
		// 以前的用法: wx://wx7375cac8ee7b7306
		wx.navigateToMiniProgram({
		  appId: h5Url.substring(5),
		  path: '',
		  envVersion: 'release',
		  success(res) {
		    // 打开成功
		  }
		})
		return true
	}
	
	const extraObj = {
		phone: uni.getStorageSync('phone'),
		unionid: uni.getStorageSync('unionId')
	}
	
	if (h5Url.includes('checkLogin=1')) {
		// 需要登录校验
		if (!extraObj.phone) {
			let loginUrl = '/pages/login/index'
			if (tabId) {
				loginUrl = `${loginUrl}?tabId=${tabId}`
			}
			uni.navigateTo({
				url: loginUrl
			})
			return true
		}
		// 替换动态参数
		const res = h5Url.matchAll(/\{(\w+)\}/g)
		let tempStr = h5Url
		if (res) {
			res.forEach(pattern => {
				const key = pattern[1]
				tempStr = tempStr.replace(pattern[0], `${key}=${extraObj[key]}`)
			})
		}

		h5Url = tempStr
	}
	
	if (hasAppIdWords) {
		// 以前的用法: wx://appid=XXX&path=XXX&{phone}&{unionid}&envVersion=xxx
		const paramsUrl = h5Url.substring(5)
		const paramsObj = parseUrlParams(paramsUrl)
		const {appid, path, ...extraData} = paramsObj
		console.log('====navigateToMiniProgram')
		console.log(appid, path, extraData)
		wx.navigateToMiniProgram({
		  appId: paramsObj.appid,
		  path: paramsObj.path,
		  extraData: extraData,
		  envVersion: paramsObj.envVersion,
		  success(res) {
		    // 打开成功
		  }
		})
		return true
	}
}